package com.qf.base.utils;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 30909
 * 异步请求的工具类
 */
public class AsyncBatchCallUtil {

    /**
     * 对外界提供方法
     */
    public static void execute(Runnable task) {
        executor.execute(task);
    }
    /**
     * 线程池
     */
    public static ExecutorService executor;

    static {
        //核心线程数
        int corePoolSize = 5;
        //最大线程数
        int maxPoolSize = 10;
        //时间
        long keepAliveTime = 10;
        //时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(10);
        //线程工厂
        ThreadFactory threadFactory = new UserThreadFactory("qianfeng");
        //拒绝策略
        RejectedExecutionHandler handler = new MyRejectPolicy();

        //实例化实例话线程池
        executor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

    }

    /**
     * 拒绝策略
     */
    static class MyRejectPolicy implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println(AsyncBatchCallUtil.class.getName()+"线程队列已经满了");
        }
    }


    /**
     * 线程工厂
     */
    static class UserThreadFactory implements ThreadFactory {

        private final String namePrefix;
        //原子
        private final AtomicInteger nextId = new AtomicInteger(1);

        public UserThreadFactory(String groupName) {
            this.namePrefix = "From" + UserThreadFactory.class.getName() + "-" + groupName + "1";
        }

        @Override
        public Thread newThread(Runnable r) {
            String name = namePrefix + nextId.getAndIncrement();
            Thread thread = new Thread(null, r,name);
            return thread;
        }
    }
}
